//
//  JDPrivateMessageViewController.swift
//  DragonWallet
//
//  Created by volantPig on 2024/6/2.
//

import UIKit
import SwiftyJSON
/// 私聊记录
class JDPrivateMessageViewController: JDBaseViewController {

    var remoteName: String?
    var remoteId: String?
    /// 当前条记录的id
    var recordId: String?
    
    var mainTableView: UITableView?
    
    var bottomContainerView: UIView?
    var cancelButton: UIButton?
    var confirmButton: UIButton?
    
    var recordModels: [JDMessageRecordModel?]?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.setupConfig()
        self.setupUIElements()
        self.getNetData()
        // Do any additional setup after loading the view.
    }
    

    func setupConfig() {
//        self.setupNavigationTitle(String.init(format: "与 %@ 的私聊记录", self.remoteName ?? ""))
//        self.title = "私聊记录"
        self.setupLeftBackItem()
    }
    
    func setupUIElements() {
        
        self.bottomContainerView = UIView()
        self.view.addSubview(self.bottomContainerView!)
        self.bottomContainerView?.snp.makeConstraints({ make in
            make.left.right.equalTo(self.view)
            make.bottom.equalTo(self.view)
            make.height.equalTo(104)
        })
        self.bottomContainerView?.backgroundColor = .white

        self.cancelButton = UIButton(type: .custom)
        self.bottomContainerView?.addSubview(self.cancelButton!)
        self.cancelButton?.snp.makeConstraints({ make in
            make.right.equalTo(self.bottomContainerView!.snp.centerX).offset(-5)
            make.centerY.equalTo(self.bottomContainerView!)
            make.left.equalTo(self.bottomContainerView!).offset(12)
            make.height.equalTo(54)
        })
        self.cancelButton?.layer.cornerRadius = 27
        self.cancelButton?.backgroundColor = color("#F5F6F8")
        self.cancelButton?.setTitle("返回", for: .normal)
        self.cancelButton?.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .regular)
        self.cancelButton?.setTitleColor(.black, for: .normal)
        self.cancelButton?.addTarget(self, action: #selector(backAction), for: .touchUpInside)
        
        self.confirmButton = UIButton(type: .custom)
        self.bottomContainerView?.addSubview(self.confirmButton!)
        self.confirmButton?.snp.makeConstraints({ make in
            make.left.equalTo(self.bottomContainerView!.snp.centerX).offset(5)
            make.right.equalTo(self.bottomContainerView!).offset(-12)
            make.height.equalTo(54)
            make.centerY.equalTo(self.bottomContainerView!)
        })
        self.confirmButton?.setTitle("发送私聊", for: .normal)
        self.confirmButton?.backgroundColor = color("#FA6161")
        self.confirmButton?.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .regular)
        self.confirmButton?.setTitleColor(.white, for: .normal)
        self.confirmButton?.layer.cornerRadius = 27
        self.confirmButton?.addTarget(self, action: #selector(sendPrivateMessageAction), for: .touchUpInside)
        
        
        self.mainTableView = UITableView(frame: .zero, style: .plain)
        self.view.addSubview(self.mainTableView!)
        self.mainTableView?.snp.makeConstraints({ make in
            make.left.right.equalTo(self.view)
            make.top.equalTo(self.view).offset(statusBarHeight+44)
            make.bottom.equalTo(self.bottomContainerView!.snp.top)
        })
        self.mainTableView?.delegate = self
        self.mainTableView?.dataSource = self
        self.mainTableView?.backgroundColor = self.commonColor
        self.mainTableView?.separatorStyle = .none
        
        self.mainTableView?.register(JDPrivateMessageTableViewCell.self, forCellReuseIdentifier: "privateMessageCell")
        self.mainTableView?.register(UITableViewCell.self, forCellReuseIdentifier: "chatCell")
        
        
        self.mainTableView?.addRefreshHeader {
            self.currentPage = 1
            self.getNetData(true)
        }
        
//        self.mainTableView?.addRefreshFooter {
//            self.currentPage += 1
//            self.getNetData(false)
//        }
        
    }
    
    override func getNetData(_ isRefresh: Bool = true) {
        
        var params = [String: Any]()
        params["receiveUserId"] = self.remoteId
        params["pageNumber"] = self.currentPage
        params["pageSize"] = 10
        params["dragonBusinessDistrictInfoId"] = self.recordId
        
        JDNetWorkRequest(.privateMessageList(params)) { responseStr in
            
            printLog("私聊记录数据:\(responseStr)")
                        
//            {"msg":"ok","data":{"records":[{"sendUserId":1,"id":3,"content":"Ceshi","sendTime":"2024-08-16 18:56:08"},{"sendUserId":1,"id":2,"content":"Erwerwerew","sendTime":"2024-08-05 14:50:39"},{"sendUserId":1,"id":1,"content":"string","sendTime":"2024-08-05 13:59:28"}],"pageNumber":1,"totalRow":3,"pageSize":10,"totalPage":1},"code":0}
            
            
            
            let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
            if commonModel?.code == "0" {
                
                let currentTitle = JSON(JSON(commonModel?.data as Any).dictionaryValue["title"] as Any).stringValue
                self.setupNavigationTitle(currentTitle)
                
                if let models = [JDMessageRecordModel].deserialize(from: responseStr, designatedPath: "data.list") {
                    
                    if isRefresh {
                        self.recordModels = models
                    } else {
                        self.recordModels?.append(contentsOf: models)
                    }
                    
                    if 0 < 10 {
                        self.mainTableView?.reloadData()
                        self.mainTableView?.noMoreData()
                    }
                }
            }
            self.mainTableView?.reloadData()
            self.mainTableView?.endRefresh()
            
        } failure: { error in
            self.mainTableView?.reloadData()
            self.mainTableView?.endRefresh()
        } error: { errorCode in
            self.mainTableView?.reloadData()
            self.mainTableView?.endRefresh()
        }
        
    }
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

    @objc func sendPrivateMessageAction() {
        printLog("发送私聊")
        let sendPrivateMessageVC = JDSendPrivateMessageViewController()
        sendPrivateMessageVC.remoteName = self.remoteName
        sendPrivateMessageVC.remoteId = self.remoteId
        sendPrivateMessageVC.recordId = self.recordId
        self.hidesBottomBarPushViewController(sendPrivateMessageVC)
    }
    
}

extension JDPrivateMessageViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.recordModels?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "chatCell")
        for subV in cell?.contentView.subviews ?? [UIView]() {
            subV.removeFromSuperview()
        }
        cell?.contentView.backgroundColor = color("#F7F7F7")
        cell?.selectionStyle = .none
        
//        let reModels = self.recordModels?.reversed() ?? [JDMessageRecordModel?]()
//        let useModels = Array(reModels) as? [JDMessageRecordModel?]

        let currentModel = self.recordModels?[indexPath.row]
        
        let portraitImageV = UIImageView()
        cell?.contentView.addChildView(portraitImageV)
        portraitImageV.makeCorner(18)

        let userName = UILabel()
        cell?.contentView.addChildView(userName)
        userName.labelConfig(textAlignment: .left, font: boldFont(14), textColor: .black, numberOfLines: 1)
        userName.text = currentModel?.nickname

        // 用户身份
        let userIdentity = UILabel()
        cell?.contentView.addChildView(userIdentity)
        userIdentity.labelConfig(textAlignment: .left, font: systemFont(10), textColor: color("#D8D8D8"), numberOfLines: 1)
        userIdentity.text = ""

        let chatLabel = JDPaddingLabel()
        cell?.contentView.addChildView(chatLabel)
        chatLabel.labelConfig(textAlignment: .left, font: UIFont.systemFont(ofSize: 14, weight: .regular), textColor: .black, numberOfLines: 0)
        chatLabel.text = currentModel?.content
        chatLabel.makeCorner(10)
        if (currentModel?.sendUserId ?? "xxx") ==  JDLoginModel.default.userId {
//            userName.text = JDLoginModel.default.nickname
//        if indexPath.row%2 == 1 {
            portraitImageV.image = UIImage.init(named: "userPortraiPlaceholder_green")
            portraitImageV.downloadImage(JDLoginModel.default.headerImg ?? "/", "userPortraiPlaceholder_green")
            // 我发的消息
            NSLayoutConstraint.activate([
                portraitImageV.rightAnchor.constraint(equalTo: cell!.contentView.rightAnchor, constant: -16),
                portraitImageV.topAnchor.constraint(equalTo: cell!.contentView.topAnchor, constant: 4),
                portraitImageV.widthAnchor.constraint(equalToConstant: 36),
                portraitImageV.heightAnchor.constraint(equalToConstant: 36)
            ])

            NSLayoutConstraint.activate([
                userName.rightAnchor.constraint(equalTo: portraitImageV.leftAnchor, constant: -8),
                userName.topAnchor.constraint(equalTo: portraitImageV.topAnchor, constant: 2),
                userName.heightAnchor.constraint(equalToConstant: 15)
            ])
            NSLayoutConstraint.activate([
                userIdentity.rightAnchor.constraint(equalTo: userName.leftAnchor, constant: -8),
                userIdentity.centerYAnchor.constraint(equalTo: userName.centerYAnchor)
            ])

            NSLayoutConstraint.activate([
                chatLabel.topAnchor.constraint(equalTo: userName.bottomAnchor, constant: 6),
                chatLabel.widthAnchor.constraint(lessThanOrEqualToConstant: screenWidth-60-16),
                chatLabel.rightAnchor.constraint(equalTo: portraitImageV.leftAnchor, constant: -8),
                chatLabel.bottomAnchor.constraint(equalTo: cell!.contentView.bottomAnchor, constant: -4),
            ])
            chatLabel.textAlignment = .right
//            chatLabel.backgroundColor = color("#25A3FF")
            chatLabel.layoutIfNeeded()
            chatLabel.backgroundColor = color("56b36e")//.customRandomColor().1
//            chatLabel.backgroundColor = UIColor.horizontalGradientColor(leftColor: color("#25A3FF"), rightColor: color("#106AFD"), colorFrame: CGRect.init(x: 0, y: 0, width: chatLabel.frame.width, height: chatLabel.frame.height))
        } else {
//            userName.text = self.remoteName
            portraitImageV.image = UIImage.init(named: "userPortraiPlaceholder")
            portraitImageV.downloadImage(currentModel?.headerImg ?? "", "userPortraiPlaceholder")
            // 别人的
            NSLayoutConstraint.activate([
                portraitImageV.leftAnchor.constraint(equalTo: cell!.contentView.leftAnchor, constant: 16),
                portraitImageV.topAnchor.constraint(equalTo: cell!.contentView.topAnchor, constant: 4),
                portraitImageV.widthAnchor.constraint(equalToConstant: 36),
                portraitImageV.heightAnchor.constraint(equalToConstant: 36)
            ])

            NSLayoutConstraint.activate([
                userName.leftAnchor.constraint(equalTo: portraitImageV.rightAnchor, constant: 8),
                userName.topAnchor.constraint(equalTo: portraitImageV.topAnchor, constant: 2),
                userName.heightAnchor.constraint(equalToConstant: 15)
            ])

            NSLayoutConstraint.activate([
                userIdentity.leftAnchor.constraint(equalTo: userName.rightAnchor, constant: 8),
                userIdentity.centerYAnchor.constraint(equalTo: userName.centerYAnchor)
            ])

            NSLayoutConstraint.activate([
                chatLabel.topAnchor.constraint(equalTo: userName.bottomAnchor, constant: 6),
                chatLabel.leftAnchor.constraint(equalTo: userName.leftAnchor, constant: 0),
                chatLabel.widthAnchor.constraint(lessThanOrEqualToConstant: screenWidth-60-16),
                chatLabel.bottomAnchor.constraint(equalTo: cell!.contentView.bottomAnchor, constant: -4)
            ])
            chatLabel.backgroundColor = .white

        }
        return cell!
        
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    
    
}
